package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.util.UserContext;
import cn.wolfcode.util.anno.RequiredPermission;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class CheckPremissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContext.getCurrentUser();
        //Employee user = (Employee)session.getAttribute("USER_IN_SESSION");
        if (employee.isAdmin()){
            return true;
        }
        //获取拦截的方法,此时后台已经帮我们封装到了handler的子类HandlerMethod中了
        HandlerMethod method = (HandlerMethod) handler;
        // 查看是否有贴自定义注解
        RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
        if (annotation == null){
            return true;
        }
        // 拿出存放在session中的属于这个用户的expression
        List<String> expressions = UserContext.getExpression();
        //List<String> expression_in_session = (List<String>)session.getAttribute("EXPRESSION_IN_SESSION");
        String expression = annotation.expression();
        // 判断当前用户是否有访问该方法的权限
        if (expressions.contains(expression)){
            return true;
        }
        // 入过都没有就返回错误页面
        ResponseBody methodAnnotation = method.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation == null){
            request.getRequestDispatcher("/errorForward.do").forward(request,response);
        }else {
            JsonResult jsonResult = new JsonResult("您没有权限", false);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
